import { useState, useMemo } from 'react';
import { Alert, Input, Modal, Space, message } from 'antd';
import CommonModal from '@/components/CommonModal';
import CommonTable from '@/components/CommonTable';
import CommonLoading from '@/components/CommonLoading';
import { CommonText } from "@/pages/OrderModule/common/components/CommonText";
import Typography from "@/pages/OrderModule/common/components/Typography";
import ShopIcons from "@/views/components/ShopIcons";
import { ORDER_STATUS } from '../../../../../common/utils/map';
import { find } from 'lodash';
import { batchInputLogisticsNoOp } from '../../../../services';

const errorMsgMaps = {
  1: '运单号不能为空',
  2: '运单号限5-20位'
}

const InputComponent = ({ index, handleRealChange }) => {
   const [errorType, setErrorType] = useState(0);

   const handleBlur = (e) => {
     const value = e.target.value?.replace(/ /g, '');
    if(!value){
      setErrorType(1);
    }else if(value?.length < 5){
      setErrorType(2);
    }
    handleRealChange(index, value);
   }

   const handleChange = () => {
     errorType && setErrorType(0);
   }

   return <>
     <Input maxLength={20} onBlur={handleBlur} onChange={handleChange} />
     {!!errorType && <div className='common-color9'>{errorMsgMaps[errorType]}</div>}
   </>
}

function renderStatusValue(val, props = {}) {
	return <Typography {...props}>{val}</Typography>;
}

export default (props) => {

  const { selectKeys, orderList, handleOk, handleCancel } = props;

  const [loading, setLoading] = useState(false);
  const data = useMemo(()=>{
    const sourceArr  = [];
    selectKeys.map(item=>{
      const obj = find(orderList, ['id', item]);
      if(obj){
        const { id, sn, ecStoreName, orderChannel, state, deliveryInfoList = [] } = obj;
        if([10, 20, 30].includes(state)){
          sourceArr.push({
            id,
            sn,
            ecStoreName,
            orderChannel,
            state,
            name: find(deliveryInfoList, ['type', 2])?.name
          })
        }
      }
    })
    return sourceArr
    return [{id: 1}, {id: 2}]
  });

  const handleRealChange = async (index, value) => {
    data[index].logisticsNo = value;
    console.log(data)
  }

  const onOk = () => {
    let hasEmpty = false, hasError = false;
    const stageArr = [];
    for (let i = 0; i < data.length; i++) {
      const logisticsNo = data[i]?.logisticsNo
       if(!logisticsNo){
        hasEmpty = true;
        break;
       }
       if(logisticsNo?.length < 5){
        hasError = true;
        break;
       }
       stageArr.push(logisticsNo);
    }
    if(hasEmpty){
      return message.info('运单号不能为空');
    }
    if(hasError){
      return message.info('请正确输入运单号');
    }
    if([...new Set(stageArr)]?.length != stageArr.length){
      return message.info('运单号填写存在重复');
    }
    handleSave();
  }

  const handleSave = async () => {
    setLoading(true);
    // console.log(data.map(item=>({
    //   logisticsNo: item.logisticsNo,
    //   orderId: item.id
    // })))
    // return
    const { data: resData, success } = await batchInputLogisticsNoOp(data.map(item=>({
      logisticsNo: item.logisticsNo,
      orderId: item.id
    })))
    setLoading(false);
    if(success){
      Modal.info({
				centered: true,
				title: "运单号提示",
				content: (
					<div style={{ color: "#333", marginTop: 24 }}>
						<Space size={24}>
							<span>成功数：{renderStatusValue(resData.successCount, { type: "success", useBold: true })}</span>
							<span>失败数：{renderStatusValue(resData.errorCount, { type: "error", useBold: true })}</span>
						</Space>
					</div>
				),
				onOk() {
					handleOk();
				}
			});
    }
  }

  const columns = [{
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    fixed: 'left',
    width: 60,
    render: (t, r, i) => i + 1,
  },
  {
    title: '系统订单号',
    dataIndex: 'sn',
    key: 'sn',
    width: 200,
  },
  {
    title: '店铺',
    dataIndex: 'ecStoreName',
    key: 'ecStoreName',
    width: 150,
    render:(text, { orderChannel }) => <CommonText
    icon={text ? <ShopIcons type={orderChannel} /> : null}
    as="s1"
    text={text ? text : "--"}
  />
  },
  {
    title: '订单状态',
    dataIndex: 'state',
    key: 'state',
    width: 100,
    render: text => ORDER_STATUS[text]
  },
  {
    title: '收货人',
    dataIndex: 'name',
    key: 'name',
    width: 100,
  },
  {
    title: '运单号',
    dataIndex: 'fileName',
    key: 'fileName',
    width: 200,
    render: (text, record, index) => <InputComponent index={index} handleRealChange={handleRealChange}/>
  },
  ]

  const tableProps = {
    data,
    columns,
    scroll: { y: 600 }
  }

  return <CommonModal
    visible={true}
    title='批量输入运单号'
    width={878}
    onOk={onOk}
    onCancel={handleCancel}
  >
    <Alert showIcon type='info' message='已有运单号的订单，将会跳过' style={{ marginBottom: '12px' }} />
    <CommonTable {...tableProps} />
    <CommonLoading loading={loading} />
  </CommonModal>
}